import django
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import Context, loader
from json.models import Note
from django.http import HttpResponse
from django.http import Http404
from functools import wraps
from django.core import serializers


def http_basic_auth(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        from django.contrib.auth import authenticate, login

        if request.META.has_key('HTTP_AUTHORIZATION'):
            authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
            if authmeth.lower() == 'basic':
                auth = auth.strip().decode('base64')
                username, password = auth.split(':', 1)
                user = authenticate(username=username, password=password)
                if user:
                    login(request, user)
        return func(request, *args, **kwargs)

    return _decorator

@http_basic_auth
@login_required
def notes(request):
    if request.method == 'GET':
        notes = Note.objects.filter(user__username=request.user.username)
        data = serializers.serialize("json", notes, fields="title,text")
        return HttpResponse(data)
    elif request.method == 'POST':
        json = request.POST["json"]
        print ("cool")
        return HttpResponse(json + "\n")



